import 'package:flutter_riverpod/flutter_riverpod.dart';

// 基础状态枚举
enum AsyncStatus {
  idle,      // 空闲状态
  loading,   // 加载中
  success,   // 成功
  error,     // 错误
  empty,     // 空数据
}

// 基础状态类
class BaseState<T> {
  final AsyncStatus status;
  final T? data;
  final String? error;
  final bool isRefreshing;

  const BaseState({
    this.status = AsyncStatus.idle,
    this.data,
    this.error,
    this.isRefreshing = false,
  });

  BaseState<T> copyWith({
    AsyncStatus? status,
    T? data,
    String? error,
    bool? isRefreshing,
  }) {
    return BaseState<T>(
      status: status ?? this.status,
      data: data ?? this.data,
      error: error ?? this.error,
      isRefreshing: isRefreshing ?? this.isRefreshing,
    );
  }

  // 便捷的状态检查方法
  bool get isIdle => status == AsyncStatus.idle;
  bool get isLoading => status == AsyncStatus.loading;
  bool get isSuccess => status == AsyncStatus.success;
  bool get isError => status == AsyncStatus.error;
  bool get isEmpty => status == AsyncStatus.empty;
  bool get hasData => data != null;
  bool get hasError => error != null;

  @override
  String toString() {
    return 'BaseState(status: $status, hasData: $hasData, error: $error, isRefreshing: $isRefreshing)';
  }
}

// 基础 Notifier 类
abstract class BaseNotifier<T> extends Notifier<BaseState<T>> {
  @override
  BaseState<T> build() {
    return const BaseState();
  }

  // 设置加载状态
  void setLoading([bool isRefreshing = false]) {
    state = state.copyWith(
      status: AsyncStatus.loading,
      error: null,
      isRefreshing: isRefreshing,
    );
  }

  // 设置成功状态
  void setSuccess(T data) {
    if (data is List && (data as List).isEmpty) {
      setEmpty();
      return;
    }

    state = state.copyWith(
      status: AsyncStatus.success,
      data: data,
      error: null,
      isRefreshing: false,
    );
  }

  // 设置错误状态
  void setError(String error) {
    state = state.copyWith(
      status: AsyncStatus.error,
      error: error,
      isRefreshing: false,
    );
  }

  // 设置空数据状态
  void setEmpty() {
    state = state.copyWith(
      status: AsyncStatus.empty,
      data: null,
      error: null,
      isRefreshing: false,
    );
  }

  // 设置空闲状态
  void setIdle() {
    state = state.copyWith(
      status: AsyncStatus.idle,
      error: null,
      isRefreshing: false,
    );
  }

  // 通用的异步操作处理
  Future<void> executeAsync(
    Future<T> Function() operation, {
    bool isRefresh = false,
    bool keepDataOnError = false,
  }) async {
    try {
      setLoading(isRefresh);
      final result = await operation();
      setSuccess(result);
    } catch (e) {
      if (!keepDataOnError) {
        setError(e.toString());
      } else {
        state = state.copyWith(
          status: AsyncStatus.error,
          error: e.toString(),
          isRefreshing: false,
        );
      }
    }
  }

  // 刷新数据
  Future<void> refresh() async {
    await loadData(isRefresh: true);
  }

  // 抽象方法，子类需要实现
  Future<void> loadData({bool isRefresh = false});
}

// 基础异步 Notifier 类（用于需要异步初始化的场景）
abstract class BaseAsyncNotifier<T> extends AsyncNotifier<BaseState<T>> {
  @override
  Future<BaseState<T>> build() async {
    return const BaseState();
  }

  // 设置状态的便捷方法
  void updateState(BaseState<T> Function(BaseState<T> current) updater) {
    final currentState = state.value ?? const BaseState();
    state = AsyncData(updater(currentState));
  }

  void setLoading([bool isRefreshing = false]) {
    updateState((current) => current.copyWith(
      status: AsyncStatus.loading,
      error: null,
      isRefreshing: isRefreshing,
    ));
  }

  void setSuccess(T data) {
    if (data is List && (data as List).isEmpty) {
      setEmpty();
      return;
    }

    updateState((current) => current.copyWith(
      status: AsyncStatus.success,
      data: data,
      error: null,
      isRefreshing: false,
    ));
  }

  void setError(String error) {
    updateState((current) => current.copyWith(
      status: AsyncStatus.error,
      error: error,
      isRefreshing: false,
    ));
  }

  void setEmpty() {
    updateState((current) => current.copyWith(
      status: AsyncStatus.empty,
      data: null,
      error: null,
      isRefreshing: false,
    ));
  }

  Future<void> executeAsync(
    Future<T> Function() operation, {
    bool isRefresh = false,
    bool keepDataOnError = false,
  }) async {
    try {
      setLoading(isRefresh);
      final result = await operation();
      setSuccess(result);
    } catch (e) {
      if (!keepDataOnError) {
        setError(e.toString());
      } else {
        updateState((current) => current.copyWith(
          status: AsyncStatus.error,
          error: e.toString(),
          isRefreshing: false,
        ));
      }
    }
  }

  Future<void> refresh() async {
    await loadData(isRefresh: true);
  }

  Future<void> loadData({bool isRefresh = false});
}